package com.luhuiguo.sso.entity;

import java.util.Set;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.ManyToMany;
import javax.persistence.Table;

import org.apache.commons.lang.builder.EqualsBuilder;
import org.apache.commons.lang.builder.HashCodeBuilder;
import org.apache.commons.lang.builder.ToStringBuilder;
import org.apache.commons.lang.builder.ToStringStyle;
import org.springframework.security.GrantedAuthority;

import com.luhuiguo.sso.entity.AuditableEntity;

@Entity
@Table(name = "t_role")
public class Role extends AuditableEntity implements GrantedAuthority {

	/**
	 * 
	 */
	private static final long serialVersionUID = 7949984803997694194L;

	@Id
	@GeneratedValue(strategy = GenerationType.AUTO)
	private Long id;

	@Column(unique = true, nullable = false)
	protected String name;

	protected String description;

	@ManyToMany(mappedBy = "roles")
	protected Set<User> users;

	public Role() {
		super();		
	}

	public Role(String name) {
		super();		
		this.name = name;
	}

	public Role(String name, String description) {
		super();		
		this.name = name;
		this.description = description;
	}

	public Long getId() {
		return id;
	}

	public void setId(Long id) {
		this.id = id;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public String getDescription() {
		return description;
	}

	public void setDescription(String description) {
		this.description = description;
	}

	public Set<User> getUsers() {
		return users;
	}

	public void setUsers(Set<User> users) {
		this.users = users;
	}

	@Override
	public String getAuthority() {
		return name;
	}

	@Override
	public String toString() {
		ToStringBuilder sb = new ToStringBuilder(this,
				ToStringStyle.SIMPLE_STYLE).append("name", this.name);
		return sb.toString();
	}

	@Override
	public boolean equals(Object other) {
		if (!(other instanceof Role)) {
			return false;
		}
		Role castOther = (Role) other;
		return new EqualsBuilder().append(this.getName(), castOther.getName())
				.isEquals();
	}

	@Override
	public int hashCode() {
		return new HashCodeBuilder().append(getName()).toHashCode();
	}

	@Override
	public int compareTo(Object o) {
		if (o != null && o instanceof GrantedAuthority) {
			GrantedAuthority rhs = (GrantedAuthority) o;
			return this.name.compareTo(rhs.getAuthority());
		}
		return -1;
	}

}
